package App.Service;

import App.Controller.BaseController;
import App.Model.User;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.security.MessageDigest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: respect_zhou@163.com
 * @Date: 2022/4/27 14:11
 */
@Slf4j
@Service
public class SMSDanMiService {
    @Value("${dan_mi.url}")
    private String dmUrl;
    @Value("${dan_mi.account_sid}")
    private String accountSid;
    @Value("${dan_mi.auth_token}")
    private String authToken;
    @Resource
    private RestTemplate restTemplate;

    //创建任务短信通知
    public boolean createTask(List<String> phones) {
        if (phones.isEmpty()) {
            return false;
        }
        return dmSendMsg(phones, null, "333611");
    }

    //开始到期短信通知
    public boolean comingTask(List<String> phones, String param) {
        if (phones.isEmpty()) {
            return false;
        }
        return dmSendMsg(phones, param, "333612");
    }

    //更新任务开始时间短信通知
    public boolean updateStartTime(List<String> phones) {
        if (phones.isEmpty()) {
            return false;
        }
        return dmSendMsg(phones, null, "333604");
    }

    private boolean dmSendMsg(List<String> phones, String param, String templateId) {
        //处理sig
        long timeMillis = System.currentTimeMillis();
        String sigCode = accountSid + authToken + String.valueOf(timeMillis);
        //多个手机号转为字符串用逗号隔开
        String phonesStr = phones.stream().map(String::valueOf).collect(Collectors.joining(","));
        //拼接参数
        StringBuilder paramBuilder = new StringBuilder();
        paramBuilder.append("accountSid=").append(accountSid);
        paramBuilder.append("&timestamp=").append(timeMillis);
        paramBuilder.append("&templateid=").append(templateId);
        paramBuilder.append("&to=").append(phonesStr);
        paramBuilder.append("&sig=").append(createMd5(sigCode));
        paramBuilder.append("&smsType=").append("100000");
        if (StringUtils.hasText(param)) {
            paramBuilder.append("&param=").append(param);
        }
        //请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<String> request = new HttpEntity<String>(paramBuilder.toString(), headers);
        //执行请求
        log.info("旦米短信请求:" + request);
        ResponseEntity<Map> response = restTemplate.exchange(dmUrl, HttpMethod.POST, request, Map.class);
        log.info("旦米短信响应:" + response);
        Map body = response.getBody();
        if (Integer.parseInt(body.get("failCount").toString()) != 0) {
            log.info("发送失败:" + body.get("failList"));
        }
        Boolean result = true;
        if (!body.get("respCode").equals("0000")) {
            result = false;
        }
        return result;
    }

    private String createMd5(String sigCode) {
        byte[] byteInput = sigCode.getBytes();
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("MessageDigest 初始化错误!" + e.getMessage());
        }
        md5.update(byteInput);
        byte[] btResult = md5.digest();
        StringBuilder sig = new StringBuilder();
        for (byte b : btResult) {
            int bt = b & 0xff;
            if (bt < 16) {
                sig.append(0);
            }
            sig.append(Integer.toHexString(bt));
        }
        return sig.toString();
    }

}
